package ar.fiuba.logger.formatRules;

import java.util.Objects;

import ar.fiuba.logger.LogMessageInterface;

/**
 * The Class LogMessageFormatRule.
 * 
 * This class implements the log message format rule. This rule prints the log message.
 */
public class LogMessageFormatRule implements FormatRuleInterface {
  /**
   * The rule code. This string will be replaced by the rule result.
   */
  private static final String ruleCode = "m";

  /*
   * (non-Javadoc)
   * 
   * @see fiuba.logger.formatRules.FormatRuleInterface#applyFormatRule(java.lang.String)
   */
  @Override
  public String applyFormatRule(String unformattedMessage, LogMessageInterface logMessage) {
    final String regex = "(?<!%)%" + ruleCode;

    String finalLogMessage = logMessage.getLogMessage();

    /*
     * If the log has an exception attached, then print the stack!
     */
    if (logMessage.getException() != null)
      finalLogMessage += "\nStack trace:" + logMessage.getException().getStackTrace();

    /*
     * Percent signs in the original log message are replaced with %% so when the percent sign
     * escape rule is applied the original message is conserved.
     */
    String escapedLogMessage = finalLogMessage;

    escapedLogMessage = escapedLogMessage.replace("%", "%%");

    return unformattedMessage.replaceAll(regex, escapedLogMessage);
  }

  /*
   * (non-Javadoc)
   * 
   * @see java.lang.Object#equals(java.lang.Object)
   */
  @Override
  public boolean equals(Object object) {
    if (this == object)
      return true;
    if (object == null)
      return false;
    if (getClass() != object.getClass())
      return false;
    return true;
  }

  /*
   * (non-Javadoc)
   * 
   * @see java.lang.Object#hashCode()
   */
  @Override
  public int hashCode() {
    return Objects.hashCode(this.getClass());
  }

}
